#include "client.h"

int recvnW(int sockfd, void *buf, int length,int fd){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,MSG_WAITALL);
        printf("p = %s\n",p);
        total += sret;
    }
    int ret=write(fd,p,length);
    ERROR_CHECK(ret,-1,"write");
    return 0;
}

int recvfile(int sockfd,const char *fliename){
    int recvflag;
    train_t recvTrain;
    train_t sendTrain;
    recvn(sockfd,&recvflag,sizeof(int)); //接受服务器文件是否存在
    if(recvflag == 0){
        int ret = access(fliename,F_OK); //查看本地文件是否存在
        if(ret == 0){
            recvn(sockfd,&recvTrain.length,sizeof(int)); //存在接受文件大小
            int fd = open(fliename,O_RDWR);
            struct stat statbuf;
            fstat(fd,&statbuf);
            int filesize = (int)(statbuf.st_size);
            
            if(filesize < recvTrain.length){  //接受的文件大小与本地的文件大小对比 判断是否断点续传
                ftruncate(fd,recvTrain.length);
                lseek(fd,filesize-1,SEEK_SET);
                off_t seek = recvTrain.length-filesize;
                sendTrain.length = filesize;
                send(sockfd,&sendTrain.length,sizeof(int),MSG_NOSIGNAL);

                recvnW(sockfd,recvTrain.buf,seek+1,fd);
                close(fd);
            }
        }else{
            int fd = open(fliename,O_RDWR|O_CREAT,0666); //本地文件不存在 直接开文件流 接受
            if(fd == -1){
                printf("The file is open failed\n");
                fflush(stdout);
            }
            off_t filesize;
            recvn(sockfd,&recvTrain.length,sizeof(int));
            filesize = recvTrain.length;
            ftruncate(fd,filesize); 
            sendTrain.length = 0;
            send(sockfd,&sendTrain.length,sizeof(int),MSG_NOSIGNAL);
            char *p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
            recvn(sockfd,p,filesize);
            printf("recv over\n");
            munmap(p,filesize);
            close(fd);
        }
    }else{
        printf("The file is not exist\n");
        fflush(stdout);
        return -1;
    }
    return 0;
}
